<template> 
 <div v-if="connectionError" class="error-alert">
      
        <button @click="setHideErrorMessage">隐藏</button>
       <!-- 消息接收模块 -->
       <!-- <section class="message-receive">
        <h3>最新消息：<span class="latest-message">{{ message }}</span></h3>
        <div class="message-history">
          <h4>历史消息记录：</h4>
          <div v-if="msgs.length === 0" class="empty-tip">暂无消息</div>
          <ul v-else class="message-list">
            <li 
              v-for="(msg, index) in msgs"
              :key="index"
              class="message-item"
            >
              {{ msg }}
            </li>
          </ul>
        </div>
      </section> -->
      <el-card  class="box-card">
  
      <div  class="message-container">
        <div class="message-list" ref="messageList2">
          <div v-for="(msg, index) in messages3" :key="index" class="message-item">
            <el-tag :type="msg.type === 'send' ? 'success' : 'info'" class="message-tag">
              {{ msg.type === 'send' ? '发送' : '接收' }}
            </el-tag>
            <span class="message-content">{{ msg.content }}</span>
          </div>
        </div>
       
      </div>
    </el-card>
        <!-- <div v-html="connectionError"></div> -->
      </div>
</template>
<script>
import VolTable from "@/components/basic/VolTable.vue";
import VolBox from '@/components/basic/VolBox.vue';
import { fa } from "element-plus/es/locales.mjs";
import axios from 'axios';
    import { HubConnectionBuilder } from '@microsoft/signalr';

  // 配置常量
  const API_BASE_URL = 'http://localhost:3000';
  const CHAT_HUB_URL = `${API_BASE_URL}/chatHub`;
  const PUSH_MSG_URL = `${API_BASE_URL}/A_UpperComputer/PushMsg`;

//这里使用的vue2语法，也可以写成vue3语法
export default {
  components: { VolTable, 'vol-box': VolBox },
  data() {
 
      return {
       
        messages3: [], // 用于存储消息记录
        row: {},
        showTable: true,
        dialogVisible: true, // 控制弹窗显示
          model1: true,
          model1Rows: [], //弹出框1传入的选中行
          model2: false,
          model2Row: {},//弹出框2点击的当前行数据
          url: 'api/EQU_COM_DEFINITION_TASK/getPageData',//指定从某个接口获取table数据
          pagination:{size: 200,sizes:[30,60,100,120,200]},
            //更多table配置见文档：http://v3.volcore.xyz/table
            //明细表格配置，从生成的vue文件中可以复制过来
            message: "等待接收消息...",
        msgs: [],
        dataInfo: {
          status1: "off",
          status2: "off"
        },
        pushContent: "",
        connection: null,
        isConnected: false,
        connectionError: null,
        reconnectAttempts: 0,
        signalRUrl: CHAT_HUB_URL,
        maxReconnectAttempts: 5
           
      };
  },
created() {
    this.initSignalRConnection();
  },
  methods: {
    // 初始化 SignalR 连接
    async initSignalRConnection() {
        try {
          debugger;
          console.log(this.http);
      //     let url = `A_UpperComputer/${action}`;
      // this.http.post(url, row, true).then((result) => {
      //   this.$message.success('执行成功');
      //   this.search();
      // });
          this.signalRUrl=this.http.ipAddress+'chatHub';//"http://192.168.110.183:8088/chatHub";
          console.log(this.signalRUrl);
          this.connection = new HubConnectionBuilder()
            .withUrl(this.signalRUrl)
            .withAutomaticReconnect()
            .build();
  
          // 注册事件处理器
          this.connection.on("showmsg", this.handleShowMessage);
          this.connection.on("updatedata", this.handleUpdateData);
          
          // 监听连接状态变化
          this.connection.onreconnecting(() => {
            this.isConnected = false;
            console.warn('Connection lost, attempting to reconnect...');
          });
  
          this.connection.onreconnected(() => {
            this.isConnected = true;
            console.info('Connection reestablished');
          });
  
          // 启动连接
          await this.connection.start();
          this.isConnected = true;
          //this.connectionError = null;
          console.info('SignalR 连接成功');
  
        } catch (error) {
          this.handleConnectionError(error);
        }
      },
  
      // 清理连接
      cleanupConnection() {
        if (this.connection) {
          this.connection.off("showmsg");
          this.connection.off("updatedata");
          this.connection.stop();
        }
      },
  
      // 处理消息显示
      handleShowMessage(msgInfo) {
        const formattedMsg = `${new Date().toLocaleTimeString()} : ${msgInfo.msgContent}`;
        this.message = formattedMsg;
        this.msgs = [...this.msgs.slice(-2), formattedMsg]; // 保留最近10条消息

        this.messages3.push({
           type: 'receive',
           content: formattedMsg
           })
          this. scrollToBottom2();
       
        },
  
      // 处理数据更新
      handleUpdateData(dataMsg) {
        this.dataInfo = { 
          ...this.dataInfo,
          ...dataMsg 
        };
      },
  
      // 发送消息
      async pushMsg() {
      
        if (!this.pushContent.trim()) {
          alert('消息内容不能为空');
          return;
        }
  
        try {
          const response = await axios.get(PUSH_MSG_URL, {
            params: { content: this.pushContent }
          });
          
          if (response.data.success) {
            this.pushContent = "";
            console.log('消息推送成功');
          }
        } catch (error) {
          console.error('消息推送失败:', error);
          alert('消息推送失败，请检查网络连接');
        }
      },
       scrollToBottom2  () {
  setTimeout(() => {
  
    if (this.$refs.messageList2) {
      this.$refs.messageList2.scrollTop = this.$.refs.messageList2.scrollHeight
    }
  }, 100)
},
      // 处理连接错误
      handleConnectionError(error) {
      
        this.isConnected = false;
        console.error('SignalR 连接失败:', error);
        
        // 自动重连逻辑
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
          setTimeout(() => {
            this.reconnectAttempts++;
            console.log(`尝试重新连接 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
            this.initSignalRConnection();
          }, 5000);
        }
      },
    //更新错误信息的方法
    setHideErrorMessage() {
      this.connectionError = null;
    },
    setErrorMessage() {
     
      this.connectionError = "*";  
    },
    onInit() {  //框架初始化配置前，

      this.columns.forEach(x => {
     
        x.hidden = false;
        x.cellStyle = (row, rowIndex, columnIndex) => {        
          return { background: "#33cc99", color: "red" }
        };
      });
    },
    calculatePercentage(numerator, denominator) {
  if (denominator === 0 || isNaN(numerator) || isNaN(denominator)) {
    return 0;
  }
  return (numerator / denominator * 100).toFixed(2);
},
     //秒转换为时分秒
 secondsToTime(seconds) {
  const hours = Math.floor(seconds / 3600).toString().padStart(2, '0');
  const minutes = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
  const remainingSeconds = (seconds % 60).toString().padStart(2, '0');
  
  return hours + ":" + minutes + ":" + remainingSeconds;
},
    openDialog() {
    
        console.log(this.dialogVisible);
      this.dialogVisible = true; // 打开弹窗
    },
    _linkView(row, column) {
  
      this.text =
        "点击单元格的弹出框，当前点击的行数据：" + JSON.stringify(row);

      this.model1 = true;
      //  this.$message.error(JSON.stringify(row));
    },

    loadBefore(params, callback) {//表格数据加载时触发


            //更多table配置见文档：http://v3.volcore.xyz/table
            //   这里也可以设置一些查询条件
            params.wheres = [{ name: "Identifier", value:this.row.OrderCode }];
            return callback(true);
        },
   

      openModel1(rows) { //弹出框1
   
        this.dialogVisible=true;
        this.model1Rows = rows;
       
       
         this.showTable = true;
        this.request2('EarlyWarning', rows);
  
         
      },
      openModel2(row, column, index) {//弹出框2
          this.request1('sendlog', row);
       
      },
      openModel3(row, column, index) {//弹出框3 显示异常
          this.request1('Faultlog', row);
       
      },
      closeModel1() {
          this.model1 = false;
      },
      closeModel2() {
          this.model2 = false;
      },
      callParent() {
          this.$emit('parentCall', $parent => {
              //$parent就是生成页面的对象，比如可以调用页面刷新，可获取的属性与方法见【生成页面文档】,$parent.xxx直接调用
              //调用刷新
              $parent.search();
              //获取所有选中的行数据
              // $parent.getSelectRows();
              this.$message.success('调用了刷新')
          })
      },
      onModelClose() {
         // this.$message.success('弹出框右上角点击x关闭事件')
      },
      request1(action, row) {
   //   let url = `api/V_PLAN_WORK_ORDER/${action}`;
   let url = `A_UpperComputer/${action}`;
      this.http.post(url, row, true).then((result) => {
    if(action=='Faultlog'){
        this.model2Row= "";
    for (let [key, value] of Object.entries(result.data)) {

            this.model2Row+=value.createOn+" "+value.content+"<br>";
  // 执行循环体代码
}
    }
   

if(action=='sendlog'){
    this.model2Row = result.data;
}
  
        this.model2 = true;
     //   this.$message.success('执行成功');
       // this.search();
      });
    },
    request2(action, row) {
    if (this.$refs.table) {
        this.row = row; //保存当前触发的行数据，下面查询时用
              this.$refs.table.load(null, true);
              this.model1 = true;
             console.log(JSON.stringify(row))
              let url = `A_UpperComputer/${action}`;
              this.tableData=[];
      this.http.post(url, row, true).then((result) => {
        for (let [key, value] of Object.entries(result.data)) {

        
      this.tableData.push(value);
           // this.tableData.push({ date: '2023-10-01', name: value.orderCode, processing_machines: '北京市朝阳区' });
            // 执行循环体代码
            }
            console.log(this.tableData);
    //     this.tableData=[
    //     { date: '2023-10-01', name: '张三', address: '北京市朝阳区' },
    //     { date: '2023-10-02', name: '李四', address: '上海市浦东新区' },
    //     { date: '2023-10-03', name: '王五', address: '广州市天河区' },
    //   ]
      });
           

          }
    },
  }
};
</script>
<style >
.icon-with-number {
  display: inline-flex;
  align-items: center;
}
.number {
  margin-left: 5px; /* 根据需要调整间距 */
}
.error-alert {
    position: fixed;
    width: 195px; /* 根据需要调整宽度 */
    bottom: 20px;
    left: 5px;
    padding: 1rem;
    background: #f56c6c;
    color: white;
    border-radius: 4px;
    animation: slideIn 0.3s;
    z-index: 1000; /* 确保在其他元素之上 */
  }
  .error-alert button {
  background: none;
  border: none;
  color: inherit;
  cursor: pointer;
  padding: 0 5px;
}


.signalr-demo {
  padding: 0px;
}

.box-card {
  max-width: 350px;
  margin: 0 auto;
  padding: 0px;
 
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-container {
  display: flex;
  flex-direction: column;
  height: 300px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 0px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 0px;
}

.message-item {
  margin-bottom: 0px;
  display: flex;
  align-items: flex-start;
}

.message-tag {
  margin-right: 0px;
  flex-shrink: 0;
}

.message-content {
  background-color: #fff;
  padding: 0px 0px;
  border-radius: 4px;
  box-shadow: 0 0px 0px rgba(0, 0, 0, 0.1);
  word-break: break-all;
}

.message-input {
  margin-top: 0px;
}
.el-card {
    --el-card-border-color: var(--el-border-color-light);
    --el-card-border-radius: 4px;
    --el-card-padding: 0px;
    --el-card-bg-color: var(--el-fill-color-blank);
}
</style>